package com.xq.shop.utils;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

public class ImageUtil {

    public static void compression(String path,String fileType) {
        try {
            // 1. Load the image
            BufferedImage image = ImageIO.read(new File(path));

            // 2. Create a writer
            ImageWriter writer =  ImageIO.getImageWritersByFormatName(fileType).next();

            // 3. Create a ImageWriteParam
            ImageWriteParam param = writer.getDefaultWriteParam();
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(0.7f); // Adjust the quality here

            // 4. Write the image
            try (ImageOutputStream output = ImageIO.createImageOutputStream(new FileOutputStream(path))) {
                writer.setOutput(output);
                writer.write(null, new IIOImage(image, null, null), param);
            }

            writer.dispose();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
